package com.ebelter.bodyfatscale.ui.activity;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import java.lang.ref.WeakReference;

/**
 * Created by ZCQ
 * 这个类没有用到Handle的Activity不要继承该类
 */

@SuppressLint("Registered")
public class BaseHandleActivity extends BaseActivity {


    public MyHandle myHandle;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        myHandle = new MyHandle(this);
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int loadLayoutById() {
        return 0;
    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void initData() {

    }

    @SuppressLint("HandlerLeak")
    class MyHandle extends Handler{

        private WeakReference<Activity> weakReference;

        MyHandle(Activity activity) {
            super(Looper.getMainLooper());
            this.weakReference = new WeakReference<>(activity);
        }

        private void setWeakReference2Null(){
            if (weakReference!=null){
                weakReference.clear();
                weakReference=null;
            }
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (weakReference!=null&&weakReference.get()!=null){
                handleMsg(msg);
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myHandle!=null){
            myHandle.removeCallbacksAndMessages(null);
            myHandle.setWeakReference2Null();
            myHandle=null;
        }
    }

    protected void handleMsg(Message msg){

    }



    public boolean sendEmptyMessage(int what){
        return sendEmptyMessageDelayed(what,0);
    }
    public boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        return myHandle != null && myHandle.sendEmptyMessageDelayed(what, delayMillis);
    }

    public boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
        return myHandle != null && myHandle.sendEmptyMessageAtTime(what, uptimeMillis);
    }

    public boolean sendMessageDelayed(Message msg, long delayMillis) {
        return myHandle != null && myHandle.sendMessageDelayed(msg, delayMillis);
    }

    public boolean sendMessage(Message msg) {
        return sendMessageDelayed(msg, 0);
    }


    public void removeMessages(int what){
        if (myHandle!=null) myHandle.removeMessages(what);
    }

}
